import paramiko

def execute_ssh_commands(hostname, port, username, password, commands):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到远程主机
        client.connect(hostname=hostname, port=port, username=username, password=password)

        # 逐个执行命令
        for command in commands:
            stdin, stdout, stderr = client.exec_command(command)
            _ = stdout.read()

    except paramiko.AuthenticationException:
        print("认证失败，请检查用户名和密码。")
    except paramiko.SSHException as e:
        print(f"SSH 连接错误: {str(e)}")
    finally:
        # 关闭 SSH 连接
        client.close()


def reset_strongswan():
    # 主机信息和要执行的命令列表
    hostname = "192.168.100.111"
    port = 22  # 默认SSH端口为22
    username = "root"
    password = "zdl"
    commands = ['/home/zdl/strongswan/IPSEC/sbin/ipsec stop', 'sleep 0.5',
                '/home/zdl/strongswan/IPSEC/sbin/ipsec start', 'sleep 0.5',
                '/home/zdl/strongswan/IPSEC/sbin/swanctl -q', 'sleep 0.5']  # 要执行的命令列表
    # 执行 SSH 连接和命令执行
    execute_ssh_commands(hostname, port, username, password, commands)

def reset_libreswan():
    # 主机信息和要执行的命令列表
    hostname = "192.168.100.111"
    port = 22  # 默认SSH端口为22
    username = "root"
    password = "zdl"
    commands = ['ipsec restart', 'sleep 1.5']  # 要执行的命令列表
    # 执行 SSH 连接和命令执行
    execute_ssh_commands(hostname, port, username, password, commands)

# reset_strongswan()
# reset_libreswan()
